<template>
<div>
  <input type="text" v-model="input1">
  <p>input1:{{input1}}</p>
  <input type="text" v-model="input2.val">
  <InjectTest></InjectTest>
</div>
</template>

<script lang="ts">
import {
  defineComponent,
  onBeforeMount, onBeforeUnmount,
  onBeforeUpdate,
  onMounted, onUnmounted,
  onUpdated, provide,
  reactive,
  ref,
  watch,
  watchEffect
} from 'vue'
import InjectTest from '@/components/InjectTest.vue'
const WatchTest = defineComponent({
  name: 'WatchTest',
  components: {
    InjectTest
  },
  setup () {
    // 生命周期函数
    onBeforeMount(() => {
      console.log('OnBeforeMount')
    })

    onMounted(() => {
      console.log('Mounted')
    })

    onBeforeUpdate(() => {
      console.log('beforeUpdate')
    })

    onUpdated(() => {
      console.log('updated')
    })

    onBeforeUnmount(() => {
      console.log('beforeUnmount')
    })

    onUnmounted(() => {
      console.log('unMountend')
    })

    const input1 = ref('Sam')
    const input2 = reactive({ val: 'Hate' })
    // watch监听
    watch([input1, () => input2.val], ([curInput1, curInput2], [prevInput1, prevInput2]) => {
      console.log('watch:', curInput1, curInput2, prevInput1, prevInput2)
    })
    const stop = watchEffect(() => {
      /* watchEffect会分析effect函数内部的引用，只要引用的数据发生变化才会触发监听回调
       无法获取prevState， 因此适合做一些effect操作（发送请求，定时器）
       与watch一样返回一个停止监听的函数
      */
      console.log('watchEffect:', input1.value, input2.val)
      // 5秒后停止监听
      setTimeout(() => {
        stop()
      }, 5000)
    })

    // Provide
    provide('input1', input1)
    return {
      input1,
      input2
    }
  }
})
export default WatchTest
</script>

<style scoped>

</style>
